package com.annhoa.filter;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class ServletFilter 注解注册过滤器：实现
 * javax.servlet.Filter接口 filterName 是过滤器的名字 urlPatterns 是需要过滤的请求 这里只过滤servlet/*
 * 下面的所有请求
 * 
 * @author annhoa
 * @effect<br>
 * 			存储编码格式、登录验证过、日志记录</br>
 * 
 */
// @WebFilter(filterName="ServletFilter", urlPatterns = {
// "/test1/*",
// "/hello1/*"
// })
@WebFilter(filterName = "ServletFilter", urlPatterns = "/users/**")
public class ServletFilter implements Filter {

	private static Logger logger = Logger.getLogger(ServletFilter.class.toString());

	// 存储编码格式信息
	// private String encode = null;

	/**
	 * Default constructor.
	 */
	public ServletFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	@Override
	public void destroy() {
		logger.warning("过滤器被销毁。");
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		logger.warning("过滤器正在执行...");
		// 此处 强转下
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		/*
		 * 判断在web.xml文件中是否配置了编码格式的信息 如果为空，则设置编码格式为配置文件中的编码格式 否则编码格式设置为GBK 暂时未配置web.xml
		 */
		// if (this.encode != null && !this.encode.equals("")) {
		// request.setCharacterEncoding(this.encode);
		// response.setCharacterEncoding(this.encode);
		// } else {
		// request.setCharacterEncoding("UTF-8");
		// response.setCharacterEncoding("UTF-8");
		// }
		// logger.warning("encode:"+this.encode);
		String requestURI = req.getRequestURI();
		logger.info("过滤到的请求--->" + requestURI);
		chain.doFilter(req, res);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	@Override
	public void init(FilterConfig fConfig) throws ServletException {
		logger.warning("初始化过滤器。");
		// 获取在web.xml文件中配置了的编码格式的信息
		// this.encode = fConfig.getInitParameter("encode");
	}

}